import { FormattedMessage, Link, useAccess } from '@umijs/max';
import { Menu, MenuProps } from 'antd';
import { getIcon } from '@/layouts/components/Menu/IconUtils';
import React, { useEffect, useState } from 'react';
import style from './index.less';

interface LevelKeysProps {
    key?: string;
    children?: LevelKeysProps[];
}

export default (props: any) => {
    const { dark, routes, defaultSelectedKeys, defaultOpenKeys } = props;
    console.log(defaultOpenKeys, defaultSelectedKeys);
    const access = useAccess();
    const filterRedirect = (arr: any[]) => {
        return arr.filter((it) => {
            if (it.redirect) {
                return false;
            }
            if (it.routes) {
                it.routes = filterRedirect(it.routes);
            }
            return true;
        });
    };
    const filteredRoutes = routes.filter((route) => {
        if ((Object.hasOwn(route, 'layout') && !route.layout) || route.redirect) {
            return false;
        }
        return !route.access || access[route.access];
    });
    const filterRedirectArr = filterRedirect(filteredRoutes)

    const buildMenu = (routes: any) => {
        return routes.map((route: any) => {
            const menu = {
                key: route.path,
                label: <FormattedMessage id={`menu.${route.name}`} defaultMessage={route.name} />,
                icon: getIcon(route.icon),
            };
            if (route.routes && route.routes.length > 0) {
                menu.children = buildMenu(route.routes);
            } else {
                menu.label = (
                    <Link to={route.path}>
                        {<FormattedMessage id={`menu.${route.name}`} defaultMessage={route.name} />}
                    </Link>
                );
            }
            return menu;
        });
    };
    const [stateOpenKeys, setStateOpenKeys] = useState(defaultOpenKeys);
    const menus = buildMenu(filterRedirectArr);

    const getLevelKeys = (items1: LevelKeysProps[]) => {
        const key: Record<string, number> = {};
        const func = (items2: LevelKeysProps[], level = 1) => {
            items2.forEach((item) => {
                if (item.key) {
                    key[item.key] = level;
                }
                if (item.children) {
                    func(item.children, level + 1);
                }
            });
        };
        func(items1);
        return key;
    };
    const levelKeys = getLevelKeys(menus as LevelKeysProps[]);

    const onOpenChange: MenuProps['onOpenChange'] = (openKeys) => {
        const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
        // open
        if (currentOpenKey !== undefined) {
            const repeatIndex = openKeys
                .filter((key) => key !== currentOpenKey)
                .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);
            setStateOpenKeys(
                openKeys
                    .filter((_, index) => index !== repeatIndex)
                    .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey]),
            );
        } else {
            // close
            setStateOpenKeys(openKeys);
        }
    };

    useEffect(() => {}, []);
    console.log(defaultOpenKeys);
    return (
        <Menu
            // defaultOpenKeys={stateOpenKeys}
            // defaultSelectedKeys={defaultSelectedKeys}
            openKeys={defaultOpenKeys}
            selectedKeys={defaultSelectedKeys}
            onOpenChange={onOpenChange}
            theme={dark ? 'dark' : 'light'}
            mode={'inline'}
            items={menus}
            className={style.menu}
        />
    );
};
